package org.jgs1904.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jgs1904.entity.Teacher;
import org.jgs1904.util.DataSourceUtil;

/**
 * 原生jdbc
 *
 * @author dyf
 * @date 2020年2月3日
 */
public class TeacherDao {

    /**
     * 查询所有
     *
     * @return
     * @throws SQLException
     * @throws ParseException
     */
    public List<Teacher> selectAll() throws SQLException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Teacher> teacherList = new ArrayList<>();

        Connection con = DataSourceUtil.getConnection();
        String sql = "select * from teacher";
        PreparedStatement pstmt = con.prepareStatement(sql);

        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            long id = rs.getLong("id");
            String name = rs.getString("name");
            byte sex = rs.getByte("sex");
            Date birthday = sdf.parse(rs.getString("birthday"));
            Integer class_id = rs.getInt("class_id");

            Teacher teacher = new Teacher(id, name, sex, birthday, class_id);
            teacherList.add(teacher);
        }

        DataSourceUtil.closeAll(con, pstmt, rs);

        return teacherList;
    }


    /**
     * 保存一条数据
     *
     * @param teacher
     * @return
     * @throws SQLException
     */
    public int insert(Teacher teacher) throws SQLException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Connection con = DataSourceUtil.getConnection();
        String sql = "insert into teacher(name,sex,birthday) value(?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(sql);

        pstmt.setString(1, teacher.getName());
        pstmt.setByte(2, teacher.getSex());
        pstmt.setString(3, sdf.format(teacher.getBirthday()));

        int result = pstmt.executeUpdate();

        return result;
    }

}
